<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
    <div>
        <el-dialog :visible="showDialog" :title="title" :close-on-click-modal="false"
        :show-close="true" append-to-body
            :close-on-press-escape="false"  :before-close="beforeClose" width="600px" :destroy-on-close="false">

            <!-- 使用动态组件 -->
            <component  :is="currentStepComponent" @cancle="cancleHandle"  :job="job"></component>

        </el-dialog>

    </div>
</template>

<script>
import { getAiStatus, startAiJob } from "@/api/ai";
import result from "./result/index.vue";
import running from "./running/index.vue";

export default {
    name: "AiSpider",
    components: {
        running,
        result,
    },

    props: {
        spiderId: { type: String, default: null, required: true },
        title: {
            type: String,
            default: 'AI导入',
        },
    },
    data() {
        return {
            showDialog: false,
            localShowClose: false,
            job: {
                status: "ready",
                message: "",
            },
            intervalId: null,
        };
    },
    mounted() {

    },
    watch: {
        showDialog(v) {
            if (!v) {
                clearInterval(this.intervalId);
                //this.startMethodInterval();
            }
        },
    },
    methods: {
        run(data, cb){
            return this.start(data, cb);
        },
        start(data, cb){
            if(!this.spiderId){
                this.$message.error("参数错误：spiderId");
                return 
            }

            // 触发任务
            // 只要开始，就强制设置job状态为running
            // 并打开窗口
            var job = {status: "running", message: "AI智能抓取中，请等待..."};
            this.job = job;
            this.showDialog = true;
            
            startAiJob(this.spiderId, data).then((res) => {
                if(res.code != 0){
                    this.showDialog = false;
                    clearInterval(this.intervalId);
                    return false;
                }

                // 如果是开始了，那么才触发轮询
                // 启动任务状态轮询;
                console.log("start interval");
                this.startMethodInterval();

                // callback
                typeof cb === "function" && cb(res);
            });
        

        },
        cancleHandle() {
            this.showDialog = false;
        },
        beforeClose() {
            clearInterval(this.intervalId);
            this.intervalId = null;
            this.showDialog = false;
            this.$emit("close")
        },
        startMethodInterval() {
            // 开始之前先清楚，防止启动多个
            if(this.intervalId){
                console.log("clear old intervalid");
                clearInterval(this.intervalId);
            }
            console.log("start job status query")
            this.intervalId = setInterval(() => {
                this.loadJobStatus();
            }, 5000); // 每隔5秒执行一次 loadJobStatus 方法

            this.loadJobStatus(); // 立即执行一次 loadJobStatus 方法
        },

        loadJobStatus() {
            // 查询任务状态
            getAiStatus(this.spiderId).then((resp) => {

                if(!this.spiderId){
                    return;
                }
                this.loading = false;

                // 接口请求失败
                if (resp.code !== 0) {
                    clearInterval(this.intervalId);
                    return false;
                }

                this.job = resp.data;
                if(!this.job){
                    return false;
                }
                switch(this.job.status){
                    case "ready":
                        clearInterval(this.intervalId);
                        this.showDialog = false;
                    case "running":
                        break;
                    case "done":
                        console.log('任务完成，停止轮询');
                        clearInterval(this.intervalId);
                        this.$emit('success', resp);
                    case "error":
                        console.log('任务失败，停止轮询');
                        clearInterval(this.intervalId);
                        this.$emit("error", resp);
                }

            });

        },
   
    },
    computed: {
        showCloseBtn: function(v){
            return this.showClose && this.localShowClose;
        },
        currentStepComponent() {
            switch (this.job.status) {
                case 'running':
                    return 'running';
                case 'done':
                    return 'result';
                case "error":
                    return 'result';
                default:
                    return 'div';
            }
        },
    },
};
</script>

<style scoped>
.ai-spider {
    display: flex;
    align-items: center;
}

.icon-ai {
    width: 14px;
    height: 14px;
    display: inline-block;
    background-size: contain;
    background-repeat: no-repeat;
    margin-right: 5px;
    background-image: url('~@/assets/images/ai-btn.svg');
}
</style>